package com.mystudy.atomic.atomicStampedReferenceTest;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * TODO: 可以用于解决CAS的ABA问题的
 *
 * @author acy
 * @since 2019/06/06 17:15
 */
public class AtomicStampedReferenceTest {
	AtomicStampedReference<Integer> reference = new AtomicStampedReference<>(100, 0);
	@Test
	public void test() throws Exception{
		Thread t1 = new Thread(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
				boolean compareAndSet = reference.compareAndSet(100, 101, reference.getStamp(), reference.getStamp() - 1);
				System.out.println("1----"+compareAndSet);
				boolean result = reference.compareAndSet(101, 100, reference.getStamp(), reference.getStamp() - 1);
				System.out.println("2----"+result);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		Thread t2 = new Thread(() -> {
			try {
				int stamp = reference.getStamp();
				System.out.println("Before sleep: stamp="+stamp);
				TimeUnit.SECONDS.sleep(2);
				boolean compareAndSet = reference.compareAndSet(100, 101, stamp, stamp + 1);
				System.out.println("3----"+compareAndSet);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		t1.start();
		t2.start();
		t1.join();
		t2.join();
	}
}
